let express = require("express");
let fs = require("fs");
let path = require("path");
let router = express.Router();

router.get("/login",(req,res)=>{
  res.sendFile( path.resolve("./views/login.html") );
})
router.get("/register",(req,res)=>{
  res.sendFile( path.resolve("./views/register.html") );
})

router.get("/dologin",(req,res)=>{
  let {username,password} = req.query;
  let data = fs.readFileSync("./persons.json");
  let arr = JSON.parse( data.toString() );
  let flag = arr.findIndex((item)=>{
    return item.username==username && item.password==password
  })
  if( flag != -1){
    res.send("登录成功");
    return;
  }else{
    res.send("账号或密码错误");
    return;
  }
})
// 响应注册表单提交
router.get("/doregister",(req,res,next)=>{
  let {username,password} = req.query;
  // undefined、null、空字符串、数字0 转为false
  // 数组、对象、非0数字，非空字符串默认转为true
  if( !username || !password ){
    next("用户名或密码不能为空");
    return;
  }

  let data = fs.readFileSync("./persons.json");
  let arr = JSON.parse( data.toString() );
  let flag = arr.findIndex((item)=>{
    return item.username == username;
  })
  if( flag !=-1 ){
    // res.send("该用户已注册");
    next("该用户已注册")
    return;
  }else{
    // 没找到相同的，继续注册流程
    let obj = {username,password};
    arr.push( obj );
    fs.writeFileSync("./persons.json", JSON.stringify(arr) );
    res.send("注册成功");
  }
})

module.exports = router;